package com.cn.xiaonuo.tcrfinance.xmpay.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.util.Date;

/**
 * 厦门国际token生成
 *
 * @author likui
 * @date 2023/11/06 13:36
 **/
public class XmPayJwtTokenUtil {

    public static String getToken(String idNo){
        // 密钥：sf9miimcp83j073rtwt5jgplow4xhigz
        XmPayJwtPayLoad payLoad = new XmPayJwtPayLoad();
        // 身份证号
        payLoad.setIdNo(idNo);
        payLoad.setPlatform("jyb");// 平台
        payLoad.setUuid(IdUtil.fastUUID());
        String token = "Bearer "+ generateOneMinuteToken(payLoad);
        return token;
    }


    public static String generateOneMinuteToken(XmPayJwtPayLoad jwtPayLoad) {
        // 有效期
        DateTime expirationDate = DateUtil.offsetMillisecond(new Date(),
                60 * 1000);
        return Jwts.builder()
                .setClaims(BeanUtil.beanToMap(jwtPayLoad))
                .setSubject(jwtPayLoad.getIdNo())
                .setIssuedAt(new Date())
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, "sf9miimcp83j073rtwt5jgplow4xhigz")
                .compact();
    }


    public static String xmPayPost(RestTemplate restTemplate,String url, String params, String idNo) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("authorization",idNo == null ? null : getToken(idNo));
        HttpEntity<String> request = new HttpEntity<String>(params, headers);
        String returnJson = restTemplate.postForObject(url, request, String.class);
        return returnJson;
    }
}
